<template>
    <div class="address">
        <!-- 头部导航 -->
        <div class="header">
            <van-nav-bar
                title="不凡"
                left-text="返回"
                left-arrow
                @click-left="onClickLeft"
            />
        </div>
        <!-- 地址列表 -->
        <div class="list">
            <van-address-list
                v-model="chosenAddressId"
                :list="list"
                default-tag-text="默认"
                @add="onAdd"
                @edit="onEdit"
            />
        </div>
    </div>
</template>

<script>
import { Toast } from 'vant';
import { getAddressListInfo } from '@/api/my/address/index'
    export default {
        data() {
            return {
                openId: localStorage.getItem('openId'),
                list: [],
            }
        },
        computed: {
            chosenAddressId: {
                get() {
                    // 如果是从结算页面跳过来的，那么带有参数id，
                    return this.$route.query.id ? this.$route.query.id : '1'
                },
                set(val) {
                    // 当前地址变化时如果带有参数，说明是从结算页跳转过来的，跳转回结算
                    if (this.$route.query.id) {
                        this.$router.push({ name: 'order', query: { id: val } })
                    }
                }
            }
        },
        methods: {
            // 返回
            onClickLeft() {
                this.$router.go(-1);
            },
            // 点击添加新地址
            onAdd() {
                this.$router.push({ name: 'addAddress' })
            },
            // 点击编辑地址
            onEdit(item) {
                this.$router.push({ name: 'addAddress', query: { id: item.id } })
            },
        },
        created() {
            // 获取地址列表
            getAddressListInfo({ openId: this.openId })
            .then(res => {
                console.log(res);
                res.data.forEach((el, index) => {
                    var obj ={
                        id: el.id,
                        name: el.name,
                        tel: el.mobile,
                        address: el.address + el.address_detail,
                        isDefault: el.is_default
                    }
                    this.list.push(obj)
                })
            })
        }
    }
</script>

<style lang="scss" scoped>
    .address{
        width: 100%;
        .header{
            background: #fff;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 9;
        }
        .list{
            margin-top: 1.226667rem;
        }
    }
</style>
